#include <iostream>
#include <algorithm>
#include <string>
#include <cstdio>
#include <vector>
#include <stack>
#include <queue>
#include <set>
using namespace std;
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
public:
    int height(TreeNode *root)
    {
        int cnt = 0;
        while (root)
        {
            root = root->left;
            cnt++;
        }
        return cnt;
    }
    int countNodes(TreeNode *root)
    {
        if (root == nullptr)
            return 0;
        int lh = height(root->left), rh = height(root->right);
        if (lh == rh)
        {
            //左子树满
            return 1 + (1 << lh) + countNodes(root->right);
        }
        else
        {
            return 1 + (1 << rh) + countNodes(root->left);
        }
    }
};